package cn.cloud.all.security.oauth2.provider;

import cn.cloud.all.security.core.Authentication;
import cn.cloud.all.security.core.GrantedAuthority;
import cn.cloud.all.security.core.context.SecurityContextHolder;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class DefaultSecurityContextAccessor implements SecurityContextAccessor {

    @Override
    public boolean isUser() {
        Authentication authentication = getUserAuthentication();
        return authentication != null;
    }

    @Override
    public Set<GrantedAuthority> getAuthorities() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return Collections.emptySet();
        }
        return Collections.unmodifiableSet(new HashSet<GrantedAuthority>(authentication.getAuthorities()));
    }

    private Authentication getUserAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oauth = (OAuth2Authentication) authentication;
            return oauth.getUserAuthentication();
        }
        return authentication;
    }
}
